<script setup>
import {
  fetchGoodsStoreList,
  deleteGoodsStore,
  fetchGoodsStoreDetail,
  saveGoodsStore,
} from '@/api/goods'
import { onMounted, ref } from 'vue'
import AddGoodsReceipt from './components/AddGoodsReceipt.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import logger from '@/utils/logger'
import { formatDateTime } from '@/utils/dayjs'

const dialogVisible = ref(false)
const currentReceipt = ref(null)
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框控制
const detailVisible = ref(false)
const detailData = ref(null)

// 审核对话框控制
const approvalDialogVisible = ref(false)
const receiptForApproval = ref(null)

// 查询条件
const queryFields = ref({
  storeNo: '',
  operatorName: '',
  startTime: '',
  endTime: '',
})

// 打开新增对话框
const openAddDialog = () => {
  currentReceipt.value = null
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = async (row) => {
  try {
    loading.value = true
    const res = await fetchGoodsStoreDetail(row.goodsStoreMId)
    if (res.success && res.data) {
      currentReceipt.value = res.data
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取编辑数据失败')
    }
  } catch (error) {
    logger.error('获取编辑数据失败', error)
    ElMessage.error('获取编辑数据失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  detailVisible.value = false
  approvalDialogVisible.value = false
}

// 获取入库单列表
const fetchReceiptData = async () => {
  try {
    loading.value = true
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      queryFields: {
        storeNo: queryFields.value.storeNo.trim() || null,
        operatorName: queryFields.value.operatorName.trim() || null,
        startTime: queryFields.value.startTime || null,
        endTime: queryFields.value.endTime || null,
      },
    }

    const res = await fetchGoodsStoreList(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取入库单列表失败')
    }
  } catch (error) {
    logger.error('获取入库单列表失败', error)
    ElMessage.error('获取入库单列表失败')
  } finally {
    loading.value = false
  }
}

// 删除入库单
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除入库单 '${row.storeNo}' 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    loading.value = true
    const res = await deleteGoodsStore(row.goodsStoreMId)
    if (res.success) {
      ElMessage.success('删除成功')
      await fetchReceiptData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      logger.error('删除入库单失败', error)
      ElMessage.error('删除入库单失败')
    }
  } finally {
    loading.value = false
  }
}

// 打开审核对话框
const openApprovalDialog = async (row) => {
  try {
    loading.value = true
    const res = await fetchGoodsStoreDetail(row.goodsStoreMId)
    if (res.success && res.data) {
      receiptForApproval.value = res.data
      approvalDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取待审核数据失败')
    }
  } catch (error) {
    logger.error('获取待审核数据失败', error)
    ElMessage.error('获取待审核数据失败')
  } finally {
    loading.value = false
  }
}

// 确认审核
const handleApprovalConfirm = async () => {
  if (!receiptForApproval.value) return
  try {
    loading.value = true
    const payload = {
      ...receiptForApproval.value,
      editType: 2,
      isCheck: true,
    }

    const res = await saveGoodsStore(payload)
    if (res.success) {
      ElMessage.success('审核成功')
      closeDialog()
      await fetchReceiptData()
    } else {
      ElMessage.error(res.msg || '审核失败')
    }
  } catch (error) {
    logger.error('审核失败', error)
    ElMessage.error('审核失败')
  } finally {
    loading.value = false
  }
}

// 查看明细
const viewDetail = async (row) => {
  try {
    loading.value = true
    const res = await fetchGoodsStoreDetail(row.goodsStoreMId)
    if (res.success && res.data) {
      detailData.value = res.data
      detailVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取详情失败')
    }
  } catch (error) {
    logger.error('获取入库单详情失败', error)
    ElMessage.error('获取入库单详情失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchReceiptData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchReceiptData()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchReceiptData()
}

// 重置搜索
const resetSearch = () => {
  queryFields.value.storeNo = ''
  queryFields.value.operatorName = ''
  queryFields.value.startTime = ''
  queryFields.value.endTime = ''
  currentPage.value = 1
  fetchReceiptData()
}

onMounted(() => {
  fetchReceiptData()
})
</script>

<template>
  <!-- 详情对话框 -->
  <el-dialog
    v-model="detailVisible"
    title="入库单详情"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddGoodsReceipt v-if="detailVisible" v-model="detailData" is-preview @close="closeDialog" />
  </el-dialog>

  <!-- 审核对话框 -->
  <el-dialog
    v-model="approvalDialogVisible"
    title="审核入库单"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddGoodsReceipt
      v-if="approvalDialogVisible"
      v-model="receiptForApproval"
      is-preview
      hide-footer
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">
          <template #icon>
            <el-icon><LineMdClose /></el-icon>
          </template>
          取消
        </el-button>
        <el-button type="primary" @click="handleApprovalConfirm">
          <template #icon>
            <el-icon><LineMdCheckAll /></el-icon>
          </template>
          审核通过
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 添加/编辑对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="currentReceipt ? '编辑入库单' : '添加入库单'"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddGoodsReceipt v-model="currentReceipt" @success="fetchReceiptData" @close="closeDialog" />
  </el-dialog>

  <div class="main-container">
    <!-- 控制区域：搜索和添加按钮 -->
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="queryFields">
          <el-form-item label="入库单号">
            <el-input
              v-model="queryFields.storeNo"
              placeholder="请输入入库单号"
              clearable
              style="width: 180px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="操作人">
            <el-input
              v-model="queryFields.operatorName"
              placeholder="请输入操作人"
              clearable
              style="width: 150px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="入库时间">
            <el-date-picker
              v-model="queryFields.startTime"
              type="date"
              placeholder="开始日期"
              style="width: 150px"
            />
            <span class="mr-2 ml-2">至</span>
            <el-date-picker
              v-model="queryFields.endTime"
              type="date"
              placeholder="结束日期"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="controller-item">
        <el-form-item>
          <el-button type="primary" @click="openAddDialog">
            <template #icon>
              <el-icon><LineMdPlus /></el-icon>
            </template>
            添加入库单
          </el-button>
        </el-form-item>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table v-loading="loading" :data="tableData" row-key="goodsStoreMId">
        <el-table-column prop="storeNo" label="入库单号" min-width="150" align="center" />
        <el-table-column label="入库时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.storeTime, 'YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column prop="operatorName" label="操作人" width="100" align="center" />
        <el-table-column label="审核状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isCheck ? 'success' : 'warning'">
              {{ row.isCheck ? '已审核' : '未审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="notes"
          label="备注"
          min-width="120"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column label="操作" width="320" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              v-if="!row.isCheck"
              type="success"
              size="small"
              @click="openApprovalDialog(row)"
            >
              <template #icon>
                <el-icon><LineMdCheckAll /></el-icon>
              </template>
              审核
            </el-button>
            <el-button
              type="primary"
              size="small"
              :disabled="row.isCheck"
              @click="openEditDialog(row)"
            >
              <template #icon>
                <el-icon><LineMdEdit /></el-icon>
              </template>
              编辑
            </el-button>
            <el-button type="info" size="small" @click="viewDetail(row)">
              <template #icon>
                <el-icon><LineMdWatchLoop /></el-icon>
              </template>
              详情
            </el-button>
            <el-popconfirm
              placement="top-start"
              confirm-button-text="确定"
              cancel-button-text="取消"
              :title="`确定要删除入库单 '${row.storeNo}' 吗？`"
              width="250"
              confirm-button-type="danger"
              :disabled="row.isCheck"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button type="danger" size="small" :disabled="row.isCheck">
                  <template #icon>
                    <el-icon><LineMdTrash /></el-icon>
                  </template>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;

    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;

    .el-table {
      flex: 1;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
